import { apply } from '@/api/llm/api'
import type { FormInstance, FormRules } from 'element-plus'
import { ElMessage } from 'element-plus'
import { reactive, ref, toRaw } from 'vue'
import { useRouter } from 'vue-router'

export default function useApply() {
  const formRef = ref<FormInstance>()
  const router = useRouter()
  const isLoading = ref(false)
  const formData = reactive({
    apiName: '',
    modelId: '',
    applyDept: '',
    applyPerson: '',
    applyPhone: '',
    applyAddr: '',
    applyEmail: '',
    applyUseScene: '',
    period: ['', ''] as any,
  })
  const validationRules: FormRules = {
    apiName: [{ required: true, message: '请输入接口名称' }],
    modelId: [{ required: true, message: '请输入申请模型' }],
    applyDept: [{ required: true, message: '请输入申请单位' }],
    applyPerson: [{ required: true, message: '请输入申请人' }],
    applyPhone: [
      { required: true, message: '请输入联系电话' },
      {
        pattern: /^((0\d{2,3}-\d{7,8})|(1[345678]\d{9}))$/,
        message: '请输入固话或手机号',
        trigger: ['blur', 'change'],
      },
    ],
    applyAddr: [{ required: true, message: '请输入联系地址' }],
    applyEmail: [
      { type: 'email', message: '请输入正确的邮箱地址' },
      {
        required: true,
        message: '请输入邮箱地址',
      },
      {
        min: 6,
        max: 50,
        message: '长度在 6 到 50 个字符',
        trigger: 'blur',
      },
    ],
    applyUseScene: [{ required: true, message: '请输入使用场景' }],
  }
  const attachments = ref<
    {
      /** 文件名 */ fileName: string
      /** 文件路径 */
      filePath: string
      /** 文件大小 */
      fileSize?: number
      /** 文件后缀 */
      fileSuffix?: string
    }[]
  >([])

  /** 提交表单 */
  async function onSubmit() {
    formRef.value.validate(async (valid) => {
      console.log('🚀 ~ file: useApply.ts:51 ~ onSubmit ~ valid:', valid)
      if (!valid) return
      const data = toRaw(formData)
      data.applyUseTimeBegin = data.period[0]
      data.applyUseTimeEnd = data.period[1]
      const { code, msg } = await apply(data)
      if (code === 200) {
        ElMessage({ message: '成功', type: 'success' })
        router.push('/llm/api')
      } else {
        ElMessage({ message: `失败：${msg}`, type: 'error' })
      }
    })
  }

  /** 重置新增的表单  */
  function resetForm() {
    formRef.value.resetFields()
  }

  return {
    isLoading,
    formData,
    attachments,
    validationRules,
    formRef,
    resetForm,
    onSubmit,
  }
}
